package com.donleo.fastdfs.service.impl;

import com.donleo.fastdfs.dao.FastDfsMapper;
import com.donleo.fastdfs.model.FastDfs;
import com.donleo.fastdfs.service.FastDfsService;
import com.luhuiguo.fastdfs.domain.StorePath;
import com.luhuiguo.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author liangd
 * @since 2021-01-25 17:42
 */
@Service
public class FastDfsServiceImpl implements FastDfsService {

    @Autowired
    private FastDfsMapper fastDfsMapper;

    @Autowired
    private FastFileStorageClient storageClient;

    @Override
    public Integer upload(MultipartFile myFile) {
        try {
            //1.获取扩展名
            String extension = FilenameUtils.getExtension(myFile.getOriginalFilename());
            //2.上传文件（上传到group1）
            StorePath uploadFile = null;

            uploadFile = storageClient.uploadFile("group1", myFile.getInputStream(), myFile.getSize(), extension);

            //3.将上传文件的信息保存到mysql中，并返回自增id
            assert uploadFile != null;
            FastDfs build = FastDfs.builder().fileName(myFile.getOriginalFilename()).filePath(uploadFile.getPath()).groupName(uploadFile.getGroup()).build();
            fastDfsMapper.add(build);
            return build.getId();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void download(Integer id, HttpServletResponse response) {
        try {
            //1.去数据库查询文件信息（文件名、在fastdfs中的位置）
            FastDfs file = fastDfsMapper.findById(id);
            //2.解决中文文件名下载后乱码的问题
            String filename = null;
            filename = URLEncoder.encode(file.getFileName(), "utf-8");
            //3.告诉浏览器 下载的文件名
            response.setHeader("Content-Disposition", "attachment; filename=" + filename + "");
            //4.将文件内容从fastdfs的输出到浏览器
            byte[] downloadFile = storageClient.downloadFile(file.getGroupName(), file.getFilePath());
            response.getOutputStream().write(downloadFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
